package com.daisuxia.risk.service;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.util.OrderNoUtil;

/**
 * 
 * 类描述：芝麻信用相关接口 <br>
 * 每次发出请求之前插入订单信息，返回后更新订单信息<br>
 * 此类不做任何业务处理，仅拼接参数请求第三方，必须使用trycath，并且不向上抛出异常以保证插入或更新的订单不会回滚<br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午03:41:28 <br>
 * 
 * @version
 * 
 */
@Service
public class JxlService implements IJxlService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;

	/**
	 * 实名认证
	 * 
	 * @param openId
	 * @param
	 * @return
	 */
	@Override
	public ServiceResult realName(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
		} catch (Exception e) {

		}
		return serviceResult;
	}

	@Override
	public ServiceResult getToken(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		String result = "";
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userPhone = params.get("userPhone");
			Object userId = params.get("userId");
			Object contacts = params.get("contacts");
			// Object contactType = params.get("contactType");
			if (userName != null && cardNum != null && userPhone != null && userId != null) {
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
				String jxlUrl = keys.get("JXL_cj_url") + "orgApi/rest/v3/applications/" + keys.get("JXL_NAME");
				String cardNo = (String) cardNum;
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.JXL);
				orders.setAct(ConstantRisk.GET_TOKEN);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(params));
				logger.info("send to get getToken " + orders.toString());
				String uid = "";
				String value = "{\"selected_website\":[],\"basic_info\":{\"name\"	:\"" + userName + "\",\"id_card_num\":\"" + cardNo
						+ "\",\"cell_phone_num\":\"" + userPhone + "\"},\"skip_mobile\":" + false + ",\"uid\":\"" + uid + "\",\"contacts\":["
						+ contacts + "]}";
				logger.info("jxl get token value:" + value);
				riskOrdersService.insert(orders);
				HashMap<String, Object> times = new HashMap<String, Object>();
				times.put("soketOut", 180000);
				times.put("connOut", 180000);
				result = WebClient.getInstance().postJsonData(jxlUrl, value, times);
				logger.info("getToken return" + result);
				try {
					orders.setReturnParams(result);
					orders.setStatus(RiskOrders.STATUS_SUC);
					riskOrdersService.update(orders);
					JSONObject jsonObject = JSONObject.fromObject(result);
					if ("65557".equals(jsonObject.getString("code"))) {
						jsonObject = jsonObject.getJSONObject("data");
						JSONObject jsonObject3 = jsonObject.getJSONObject("datasource");
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, jsonObject.getString("token"), jsonObject3.getString("website"));
					} else if ("65545".equals(jsonObject.getString("code"))) {
						serviceResult = new ServiceResult("100", "紧急联系人手机号码不合法");
					} else {
						serviceResult = new ServiceResult("100", jsonObject.getString("message"));
					}
				} catch (Exception e) {
					logger.error("getToken local logic error ", e);
					serviceResult = new ServiceResult("300", "解析数据出错");
				}
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getToken error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult getCaptcha(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		String result = "";
		try {
			Object userPhone = params.get("userPhone");
			Object website = params.get("website");
			Object password = params.get("password");
			Object queryPwd = params.get("queryPwd");
			Object userId = params.get("userId");
			Object token = params.get("token");
			if (token != null && website != null && userId != null) {
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
				String jxlUrl = keys.get("JXL_cj_url") + "orgApi/rest/v2/messages/collect/req";
				RiskOrders orders = new RiskOrders();
				String orderNo = OrderNoUtil.getInstance().getUUID();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.JXL);
				orders.setAct(ConstantRisk.APPLY_COLLECT);
				orders.setOrderNo(orderNo);
				orders.setReqParams(JSON.toJSONString(params));
				logger.info("send to get applyCollect " + orders.toString());
				String value = "{\"token\":\"" + token + "\",\"account\":\"" + userPhone + "\",\"password\":\"" + password + "\",\"website\":\""
						+ website + "\"}";

				logger.info("jxl get applyCollect value:" + value);
				riskOrdersService.insert(orders);
				HashMap<String, Object> times = new HashMap<String, Object>();
				times.put("soketOut", 180000);
				times.put("connOut", 180000);
				result = WebClient.getInstance().postJsonData(jxlUrl, value, times);
				logger.info("get applyCollect result=" + result);
				try {
					orders.setReturnParams(result);
					orders.setStatus(RiskOrders.STATUS_SUC);
					riskOrdersService.update(orders);
					JSONObject jsonObject3 = JSONObject.fromObject(result);
					if (jsonObject3.getBoolean("success")) {
						JSONObject jsonObject2 = JSONObject.fromObject(result);
						JSONObject jsonObject = jsonObject2.getJSONObject("data");
						String code1 = jsonObject.getString("process_code");
						if ("10002".equals(code1)) {
							serviceResult = new ServiceResult("200", "短信已发送至您手机，请耐心等待并尽快输入验证码完成验证");
						} else if ("10008".equals(code1)) {
							serviceResult = new ServiceResult("100", "开始采集数据!");
						} else if ("10022".equals(code1)) {
							String type = "";
							String queryPwdtype = "";
							if ("chinamobilebj".equals(website)) {
								type = "\",\"type\":\"" + ConstantRisk.SUBMIT_QUERYPASSWORD;
								queryPwdtype = "\",\"queryPwd\":\"" + queryPwd;
							}
							value = "{\"token\":\"" + token + "\",\"account\":\"" + userPhone + "\",\"password\":\"" + password + "\",\"website\":\""
									+ website + type + queryPwdtype + "\"}";
							result = WebClient.getInstance().postJsonData(jxlUrl, value, times);
							orders.setReturnParams(result);
							orders.setStatus(RiskOrders.STATUS_SUC);
							riskOrdersService.update(orders);
							JSONObject jsonObject4 = JSONObject.fromObject(result);
							if (jsonObject4.getBoolean("success")) {
								JSONObject jsonObject6 = jsonObject2.getJSONObject("data");
								String code2 = jsonObject6.getString("process_code");
								if ("10002".equals(code2)) {
									serviceResult = new ServiceResult("200", "短信已发送至您手机，请耐心等待并尽快输入验证码完成验证");
								} else if ("10008".equals(code2)) {
									serviceResult = new ServiceResult("100", "开始采集数据!");
								} else {
									serviceResult = new ServiceResult("300", jsonObject3.getString("message") == null ? "未知异常" : jsonObject3
											.getString("message"));
								}
							}
						} else {
							serviceResult = new ServiceResult("300", jsonObject.getString("content"));
						}

					} else {
						serviceResult = new ServiceResult("300", jsonObject3.getString("message"));
					}
				} catch (Exception e) {
					logger.error("getHZ local logic error params=" + params, e);
					serviceResult = new ServiceResult("300", "解析数据出错");
				}
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getOpenId error ,params=" + params, e);
		}
		return serviceResult;
	}

	/**
	 * 提交验证码<br>
	 * code为200时，msg是聚信立信息；<br>
	 * 提交验证码请求，则开始采集数据
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@Override
	public ServiceResult applyCollect(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		String result = "";
		try {
			Object userPhone = params.get("userPhone");
			Object website = params.get("website");
			Object password = params.get("password");
			Object queryPwd = params.get("queryPwd");
			Object userId = params.get("userId");
			Object token = params.get("token");
			Object CAPTCHA = params.get("CAPTCHA");
			if (token != null && website != null && userId != null) {
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
				String jxlUrl = keys.get("JXL_cj_url") + "orgApi/rest/v2/messages/collect/req";
				RiskOrders orders = new RiskOrders();
				String orderNo = OrderNoUtil.getInstance().getUUID();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.JXL);
				orders.setAct(ConstantRisk.APPLY_COLLECT);
				orders.setOrderNo(orderNo);
				orders.setReqParams(JSON.toJSONString(params));
				logger.info("send to get applyCollect " + orders.toString());
				String cap = "";
				String type = "";
				if (CAPTCHA != null && StringUtils.isNotBlank(CAPTCHA.toString())) {
					if ("chinamobilebj".equals(website)) {
						if (queryPwd != null) {
							cap = "\",\"type\":\"" + ConstantRisk.SUBMIT_QUERYPASSWORD + "\",\"captcha\":\"" + CAPTCHA + "\",\"queryPwd\":\""
									+ queryPwd;
						} else {
							type = "SUBMIT_CAPTCHA";
							cap = "\",\"captcha\":\"" + CAPTCHA + "\",\"type\":\"" + type;
						}
					} else {
						type = "SUBMIT_CAPTCHA";
						cap = "\",\"captcha\":\"" + CAPTCHA + "\",\"type\":\"" + type;
					}
				}
				String value = "{\"token\":\"" + token + "\",\"account\":\"" + userPhone + "\",\"password\":\"" + password + "\",\"website\":\""
						+ website + cap + "\"}";

				riskOrdersService.insert(orders);
				HashMap<String, Object> times = new HashMap<String, Object>();
				times.put("soketOut", 180000);
				times.put("connOut", 180000);
				result = WebClient.getInstance().postJsonData(jxlUrl, value, times);
				logger.info("get applyCollect result=" + result);
				try {
					orders.setReturnParams(result);
					orders.setStatus(RiskOrders.STATUS_SUC);
					riskOrdersService.update(orders);
					JSONObject jsonObject3 = JSONObject.fromObject(result);
					if (jsonObject3.getBoolean("success")) {
						JSONObject jsonObject2 = JSONObject.fromObject(result);
						JSONObject jsonObject = jsonObject2.getJSONObject("data");
						String process_code = jsonObject.getString("process_code");
						if ("10002".equals(process_code)) {

							serviceResult = new ServiceResult("100", "需要验证码");
						} else if ("10008".equals(process_code)) {
							serviceResult = new ServiceResult("200", "开始采集数据!");
						} else if ("10006".equals(process_code)) {
							serviceResult = new ServiceResult("102", jsonObject.getString("content"));
						} else {
							serviceResult = new ServiceResult("300", "其他异常！");
						}
					} else {
						serviceResult = new ServiceResult("300", jsonObject3.getString("message"));
					}
				} catch (Exception e) {
					logger.error("getHZ local logic error ", e);
					serviceResult = new ServiceResult("300", "解析数据出错");
				}
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getOpenId error ,params=" + params, e);
		}
		return serviceResult;
	}

	/**
	 * 查询报告
	 */
	@Override
	public ServiceResult findUserReport(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		String result = "";
		try {
			Object userId = params.get("userId");
			Object token = params.get("token");
			if (token != null && userId != null) {

				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
				String jxlUrl = keys.get("JXL_cj_url") + "api/access_report_data_by_token?";
				RiskOrders orders = new RiskOrders();
				String orderNo = OrderNoUtil.getInstance().getUUID();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.JXL);
				orders.setAct(ConstantRisk.GET_USER_REPORT);
				orders.setOrderNo(orderNo);
				orders.setReqParams(JSON.toJSONString(params));
				logger.info("send to get applyCollect " + orders.toString());
				String value = "access_token=" + keys.get("JXL_token") + "&token=" + token + "&client_secret=" + keys.get("JXL_BZM");
				jxlUrl = jxlUrl + value;
				riskOrdersService.insert(orders);
				result = new WebClient().doGet(jxlUrl);
				logger.info("send to findUserReport " + orders.toString());
				try {
					orders.setReturnParams(result);
					JSONObject jsonObject = JSONObject.fromObject(result);
					if (jsonObject.getBoolean("success")) {
						orders.setStatus(RiskOrders.STATUS_SUC);
						serviceResult = new ServiceResult("200", result);
					} else {
						serviceResult = new ServiceResult("300", "查询报告失败");
					}
					riskOrdersService.update(orders);
					logger.info("get findUserReport result=" + result);
				} catch (Exception e) {
					logger.error("getHZ findUserReport error ", e);
					serviceResult = new ServiceResult("300", "解析数据出错");
				}
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getOpenId error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult createJxl(HashMap<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}

}